<script setup lang="ts">
import dayjs from 'dayjs'

const props = defineProps<{
  initialValue: dayjs.Dayjs
}>()

defineEmits(['confirm', 'cancel'])

const data = [
  Array.from({ length: 10 }, (_, i) => i).map((_, i) => {
    const date = dayjs().add(i, 'day')
    switch (i) {
      case 0:
        return { label: '今天', rawValue: date.format('YYYY-MM-DD') }
      case 1:
        return { label: '明天', rawValue: date.format('YYYY-MM-DD') }
      default:
        return { label: date.format('M月D日'), rawValue: date.format('YYYY-MM-DD') }
    }
  }),
  Array.from({ length: 24 }, (_, i) => i.toString().padStart(2, '0')),
  Array.from({ length: 60 }, (_, i) => i.toString().padStart(2, '0')),
]

const selection = ref([
  props.initialValue.diff(dayjs(), 'day'),
  props.initialValue.hour(),
  props.initialValue.minute(),
])

const selectedDate = computed(() => {
  const date = data[0][selection.value[0]] as { label: string, rawValue: string }
  const hour = data[1][selection.value[1]]
  const minute = data[2][selection.value[2]]
  return dayjs(`${date.rawValue} ${hour}:${minute}`)
})

const displayedSelectedTime = computed(() => {
  const date = data[0][selection.value[0]] as { label: string, rawValue: string }
  const hour = data[1][selection.value[1]]
  const minute = data[2][selection.value[2]]
  return `${date.label} ${hour}:${minute}`
})

function handleChange(e: any) {
  selection.value = e.detail.value
}
</script>

<template>
  <view class="rounded-t-50rpx bg-white py-40rpx">
    <view class="px-40rpx">
      <view class="text-28rpx text-#666666 font-bold leading-28rpx">
        您的预计出发时间是...
      </view>
      <Spacer height="34" />
      <view class="text-34rpx text-black font-bold leading-34rpx">
        {{ displayedSelectedTime }} 出发
      </view>
    </view>
    <Spacer height="44" />
    <Divider width="670" />
    <Spacer height="80" />
    <picker-view :value="selection" class="h-300rpx w-full" @change="handleChange">
      <picker-view-column v-for="column, i in data" :key="i">
        <view v-for="item, j in column" :key="j" class="h-32rpx flex items-center justify-center">
          {{ typeof item === 'string' ? item : item.label }}
        </view>
      </picker-view-column>
    </picker-view>
    <Spacer height="180" />
    <view class="flex items-center justify-center">
      <RGButton type="secondary" :width="250" @tap="$emit('cancel')">
        稍后再说
      </RGButton>
      <Spacer width="24" />
      <RGButton :width="423" @tap="$emit('confirm', { date: selectedDate, str: displayedSelectedTime })">
        确认出发时间
      </RGButton>
    </view>
    <Spacer height="44" />
  </view>
</template>
